package com.hjxr.quota.sdoc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjxr.common.utils.StringUtils;
import com.hjxr.quota.sdoc.domain.Sdoc;
import com.hjxr.quota.sdoc.mapper.SdocMapper;
import com.hjxr.quota.sdoc.service.SdocSevice;
import com.hjxr.quota.util.FileUtils;
import com.hjxr.quota.util.PageUtil;
import com.hjxr.quota.util.Query;
import com.hjxr.sysadmin.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Service
public class SdocServiceImpl extends ServiceImpl<SdocMapper, Sdoc> implements SdocSevice {

    @Value("${hjxr.profile}")
    private String proFilePath;
    @Autowired
    private TokenService tokenService;


    @Override
    public PageUtil selectSdocList(Map<String, Object> params) {
        //参数查询暂时没写
        QueryWrapper<Sdoc> wrapper = new QueryWrapper<Sdoc>();
        String docName = (String) params.get("docName");
        if (StringUtils.isNotBlank(docName)) {
            wrapper.like("DOC_NAME", docName);
        }
        IPage<Sdoc> page = this.page(new Query<Sdoc>().getPage(params), wrapper);
        return new PageUtil(page);
    }

    @Override
    public Integer fileInformationToDb(String fileName, String finalName, HttpServletRequest request) {
        Sdoc sdoc = new Sdoc();
        String shortFileName = fileName.substring(0, fileName.lastIndexOf("."));
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//判断文件类型
        if (fileType.equalsIgnoreCase("xls") || fileType.equalsIgnoreCase("xlsx")) {
            fileType = "excel";
        }
        sdoc.setDocName(shortFileName);
        sdoc.setDocUrl(proFilePath+"//"+finalName);
        if(FileUtils.isContainChinese(shortFileName)){
            sdoc.setDocTableCode("THEME_" + FileUtils.getPinYinHeadChar(shortFileName));
        }else{
            sdoc.setDocTableCode(shortFileName);
        }
        sdoc.setDocDescription("");
        sdoc.setIsExistTable(0);
        sdoc.setIsExistData(0);
        sdoc.setUpdateBy(tokenService.getLoginUser(request).getUsername());
        sdoc.setUpdateDate(new Date());
        sdoc.setDocType(fileType);
        if(save(sdoc)){
            return sdoc.getId();
        }
        return 0;
    }
}
